using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 问诊订单详情查询处理器
    /// </summary>
    public class ConsultationOrderDetailQueryHandler : IRequestHandler<ConsultationOrderDetailQuery, ConsultationOrderDetailResult>
    {
        private readonly IConfiguration _configuration;

        public ConsultationOrderDetailQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<ConsultationOrderDetailResult> Handle(ConsultationOrderDetailQuery request, CancellationToken cancellationToken)
        {
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                // 查询订单基本信息和患者信息
                var orderSql = @"
                    SELECT 
                        p.Name, p.Gender, p.Age, p.Phone, 
                        co.DiseaseDescription, co.MedicalSituation, co.AppointmentTime, co.SubmitTime,
                        co.OrderNo, co.OrderType, co.Status AS OrderStatus, 
                        co.OrderAmount AS PayableAmount, 0 AS CouponAmount, co.OrderAmount AS ActualPayment, 
                        co.CreateTime, 'Online' AS PaymentMethod, co.CreateTime AS PaymentTime,
                        co.RefundReason, co.RefundAmount,
                        ci.ConsultationTime, ci.CallDuration, ci.PatientRating, ci.PatientComment,
                        co.Id
                    FROM consultationordermodel co
                    LEFT JOIN patientmodel p ON co.PatientId = p.Id
                    LEFT JOIN consultationinfomodel ci ON co.ConsultationInfoId = ci.Id
                    WHERE co.OrderNo = @OrderNo AND co.IsDeleted = 0";

                var orderDetail = await connection.QueryFirstOrDefaultAsync<dynamic>(orderSql, new { OrderNo = request.OrderNo });

                if (orderDetail == null)
                {
                    return null;
                }

                var result = new ConsultationOrderDetailResult
                {
                    Patient = new PatientInfoDto
                    {
                        Name = orderDetail.Name,
                        Gender = orderDetail.Gender?.ToString(), // 添加显式转换
                        Age = orderDetail.Age,
                        Phone = orderDetail.Phone,
                        DiseaseDescription = orderDetail.DiseaseDescription,
                        MedicalSituation = orderDetail.MedicalSituation,
                        AppointmentTime = orderDetail.AppointmentTime,
                        SubmitTime = orderDetail.SubmitTime
                    },
                    OrderInfo = new ConsultOrderInfoDto
                    {
                        OrderNo = orderDetail.OrderNo,
                        OrderType = orderDetail.OrderType?.ToString(), // 添加显式转换
                        OrderStatus = ConvertOrderStatus(orderDetail.OrderStatus),
                        PayableAmount = orderDetail.PayableAmount,
                        CouponAmount = orderDetail.CouponAmount,
                        ActualPayment = orderDetail.ActualPayment,
                        CreateTime = orderDetail.CreateTime,
                        PaymentMethod = orderDetail.PaymentMethod,
                        PaymentTime = orderDetail.PaymentTime,
                        RefundReason = orderDetail.RefundReason,
                        RefundAmount = orderDetail.RefundAmount
                    },
                    ConsultInfo = new ConsultInfoDto
                    {
                        ConsultationTime = orderDetail.ConsultationTime,
                        CallDuration = orderDetail.CallDuration?.ToString(), // 添加显式转换
                        PatientRating = orderDetail.PatientRating,
                        PatientComment = orderDetail.PatientComment
                    }
                };

                // 查询问诊记录
                if (orderDetail.ConsultationTime != null)
                {
                    /* 暂时注释此段代码，等待确认正确的表名
                    var consultRecordSql = @"
                        SELECT cr.Id, cr.Time, cr.Type, cr.Content, cr.SenderType
                        FROM consultationrecord cr
                        WHERE cr.ConsultationOrderId = @ConsultationOrderId AND cr.IsDeleted = 0
                        ORDER BY cr.Time ASC";

                    var consultRecords = await connection.QueryAsync<ConsultRecordDto>(
                        consultRecordSql, new { ConsultationOrderId = orderDetail.Id });
                    
                    result.ConsultInfo.ConsultRecords.AddRange(consultRecords);
                    */
                    
                    // 临时返回空集合
                    result.ConsultInfo.ConsultRecords = new List<ConsultRecordDto>();
                }

                return result;
            }
        }

        /// <summary>
        /// 转换订单状态码为状态文本
        /// </summary>
        private string ConvertOrderStatus(int status)
        {
            switch (status)
            {
                case 1:
                    return "待支付";
                case 2:
                    return "进行中";
                case 3:
                    return "已完成";
                case 4:
                    return "已取消";
                case 5:
                    return "已退诊";
                default:
                    return "未知";
            }
        }
    }
} 